home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2054 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: info.uah.edu!oreo!gbacon
  2. From: gbacon@oreo (Greg Bacon)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Examples of using "volatile"?
  5. Date: 18 Jan 1996 20:03:05 GMT
  6. Organization: The University of Alabama in Huntsville
  7. Message-ID: <4dm91p$bsi@info.uah.edu>
  8. References: <4djoj2$mr1@post.gsfc.nasa.gov>
  9. Reply-To: gbacon@CS.UAH.Edu
  10. NNTP-Posting-Host: oreo.aspire.cs.uah.edu
  11. X-Newsreader: TIN [version 1.2 PL2]
  12.  
  13. Stephen Maher (Stephen.Maher@gsfc.nasa.gov) wrote:
  14. : Hi,
  15.  
  16. : I'd like a concrete example(s) illustrating a reason to
  17. : use the "volatile" type qualifier.
  18.  
  19. : I understand the *theory* behind volatile (e.g., to
  20. : avoid unwanted side-effects?).  I also realize it's
  21. : probably implementation dependent. But some examples
  22. : from any implementation should help me understand
  23. : its use a little better.
  24.  
  25. : Thanks,
  26.  
  27. : Steve
  28.  
  29. OK... say for example you have this:
  30.  
  31. void foo(void)
  32. {
  33.    int i = 7;
  34.  
  35.    if (i == 7)
  36.    {
  37.       /* do something */
  38.    }
  39. }
  40.  
  41. Most optimizers will go ahead and lose the comparison since i _has_
  42. to be equal to 7, right?  Well, not always.. say you have some
  43. interrupt handler (ahh, the random joy of interrupts) that might
  44. come in and modify the value of i (highly unlikely, I admit, but this
  45. is a highly oversimplified example).  Well, if the optimizer
  46. cuts out the test, then it won't matter whether the handler came
  47. in.  The correct version of foo() for this app would look like this:
  48.  
  49. void foo(void)
  50. {
  51.    volatile int i = 7;
  52.  
  53.    if (i == 7)
  54.    {
  55.       /* do something */
  56.    }
  57. }
  58.  
  59. Basically, like most modifiers, volatile is a hint to the compiler
  60. that the value of i could change at any time, and not to take its
  61. value for granted.  Of course, the compiler could ignore you since
  62. it's only a hint, but that wouldn't be a very good compiler :)
  63.  
  64. Hope this helps,
  65. Greg
  66. --
  67. Greg Bacon <gbacon@cs.uah.edu>
  68. University of Alabama in Huntsville
  69. CS Department Systems Support Team
  70.